<template>
  <div class="app-container">
    <eHeader :sup_this="sup_this" :param-bean="paramBean" />
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="10" :xl="17">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
            <div id="opt" style="float: right">
              <el-radio-group v-model="opt" size="mini">
                <el-radio-button label="用户分配"/>
                <el-radio-button label="菜单分配"/>
                <el-radio-button label="权限分配"/>
                <el-radio-button label="组织分配"/>
              </el-radio-group>
            </div>
          </div>
          <el-table v-loading="loading" :data="data.rtnList" highlight-current-row size="small" style="width: 100%;" @current-change="handleCurrentChange">
            <el-table-column prop="roleName" label="名称"/>
            <el-table-column :show-overflow-tooltip="true" prop="rmk" label="描述"/>
            <el-table-column :show-overflow-tooltip="true" prop="createDate" label="创建日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="checkPermission(['SYS_ADMIN','ROLE_ALL','ROLE_EDIT','ROLE_DELETE'])" label="操作" width="130px" align="center">
              <template slot-scope="scope">
                <edit v-permission="['SYS_ADMIN','ROLES_ALL','ROLE_EDIT']" :data="scope.row" :sup_this="sup_this"/>
                <el-popover
                  v-permission="['SYS_ADMIN','ROLE_ALL','ROLE_DELETE']"
                  :ref="scope.row.id"
                  placement="top"
                  width="180">
                  <p>确定删除本条数据吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                    <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
                  </div>
                  <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"/>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :total="total"
            style="margin-top: 8px;"
            layout="total, prev, pager, next, sizes"
            @size-change="sizeChange"
            @current-change="pageChange"/>
        </el-card>
      </el-col>
      <!-- 授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="14" :xl="7">
        <el-card v-show="opt === '用户分配'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配用户" placement="top">
              <span class="role-span">用户分配</span>
            </el-tooltip>
            <el-button
              v-permission="['SYS_ADMIN','ROLE_ALL','ROLE_EDIT']"
              :disabled="!showButton"
              :loading="userLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="addUser">增加用户</el-button>
            <userSelectList ref="userSelectList" :sup_this="sup_this" />
          </div>
          <roleOrgList v-show="currentId != '' " ref="roleOrgList" :sup_this="sup_this" />
        </el-card>
        <el-card v-show="opt === '菜单分配'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              v-permission="['SYS_ADMIN','ROLE_ALL','ROLE_EDIT']"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu">保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            accordion
            show-checkbox
            node-key="id"/>
        </el-card>
        <el-card v-show="opt === '权限分配'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配权限" placement="top">
              <span class="role-span">权限分配</span>
            </el-tooltip>
            <el-button
              v-permission="['SYS_ADMIN','ROLE_ALL','ROLE_EDIT']"
              :disabled="!showButton"
              :loading="privLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="savePriv">保存</el-button>
          </div>
          <el-tree
            ref="priv"
            :data="privs"
            :default-checked-keys="privIds"
            :props="defaultProps"
            show-checkbox
            accordion
            node-key="id"/>
        </el-card>
        <el-card v-show="opt === '组织分配'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配组织" placement="top">
              <span class="role-span">组织分配</span>
            </el-tooltip>
            <el-button
              v-permission="['SYS_ADMIN','ROLE_ALL','ROLE_EDIT']"
              :disabled="!showButton"
              :loading="orgLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveOrg">保存</el-button>
          </div>
          <el-tree
            ref="org"
            :data="orgs"
            :default-checked-keys="orgIds"
            :props="defaultProps"
            :check-strictly="true"
            default-expand-all
            show-checkbox
            accordion
            node-key="id"/>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import { del, loadDataUrl } from '@/api/role'
import { getAllPrivs } from '@/api/priv'
import { getAllMenusTree } from '@/api/menu'
import { getOrgSetsByCpyCode } from '@/api/orgSet'
import { parseTime } from '@/utils/index'
import eHeader from './module/header'
import edit from './module/edit'
import { saveUser, savePriv, saveMenu, saveOrg } from '@/api/role'
import roleOrgList from './module/roleOrgList'
import userSelectList from '../user/module/userSelectList'

export default {
  components: { eHeader, edit, roleOrgList, userSelectList },
  mixins: [initData],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentId: '',
      privLoading: false, menuLoading: false, orgLoading: false, userLoading: false,
      showButton: false, opt: '菜单分配',
      delLoading: false, sup_this: this,
      privs: [], privIds: [],
      menus: [], menuIds: [],
      orgs: [], orgIds: []
    }
  },
  created() {
    this.getPrivs()
    this.getOrgs()
    this.getMenus()
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    checkPermission,
    beforeInit() {
      this.$refs.priv.setCheckedKeys([])
      this.$refs.menu.setCheckedKeys([])
      this.showButton = false
      this.url = loadDataUrl()
      return true
    },
    afterInit() {
      this.currentId = ''
    },
    subDelete(id) {
      this.delLoading = true
      const data = { idList: [{ id: id }] }
      del(data).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.init()
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err)
      })
    },
    getPrivs() {
      getAllPrivs().then(res => {
        this.privs = res.data
      })
    },
    getMenus() {
      getAllMenusTree().then(res => {
        this.menus = res.data
      })
    },
    getOrgs() {
      getOrgSetsByCpyCode().then(res => {
        this.orgs = res.data
      })
    },
    handleCurrentChange(val) {
      const _this = this
      // 清空权限与菜单的选中
      _this.$refs.priv.setCheckedKeys([])
      _this.$refs.org.setCheckedKeys([])
      _this.$refs.menu.setCheckedKeys([])
      // 初始化
      _this.menuIds = []
      _this.privIds = []
      _this.orgIds = []
      _this.currentId = ''
      if (val) {
        // 保存当前的角色id
        _this.currentId = val.id
        // 点击后显示按钮
        _this.showButton = true
        // 菜单数据需要特殊处理
        const menus = val.roleMenuVOList
        menus.forEach(function(row, index) {
          _this.menuIds.push(row.menuId)
        })
        // 处理权限数据
        const privs = val.rolePrivVOList
        privs.forEach(function(row, index) {
          _this.privIds.push(row.privId)
        })
        // 处理组织数据
        const orgs = val.roleOrgVOList
        orgs.forEach(function(row, index) {
          _this.orgIds.push(row.orgId)
        })
        // 处理用户与部门数据
        const _thisRole = _this.$refs.roleOrgList
        _thisRole.roleId = _this.currentId
        _thisRole.init()
      }
    },
    doUserSelectCallback(selectedRows, userSelectObj) {
      const data = { busMainData: { id: this.currentId, roleUserVOList: [] }}
      selectedRows.forEach(row => {
        const tmpMenu = { userId: row.id, userAccount: row.userAccount }
        data.busMainData.roleUserVOList.push(tmpMenu)
      })
      saveUser(data).then(res => {
        userSelectObj.cancel()
        userSelectObj.loading = false
        this.$refs.roleOrgList.init()
      }).catch(err => {
        userSelectObj.loading = false
        console.log(err)
      })
    },
    addUser() {
      const _this = this.$refs.userSelectList
      _this.init()
      _this.dialog = true
    },
    saveOrg() {
      this.orgLoading = true
      const data = { busMainData: { id: this.currentId, roleOrgVOList: [] }}
      this.$refs.org.getCheckedNodes().forEach(function(tmpNode, index) {
        const tmpMenu = { orgId: tmpNode.id, orgCode: tmpNode.orgCode }
        data.busMainData.roleOrgVOList.push(tmpMenu)
      })
      saveOrg(data).then(res => {
        this.orgLoading = false
        // this.update()
      }).catch(err => {
        this.orgLoading = false
        console.log(err)
      })
    },
    savePriv() {
      this.privLoading = true
      const data = { busMainData: { id: this.currentId, rolePrivVOList: [] }}
      this.$refs.priv.getCheckedNodes().forEach(function(tmpNode, index) {
        const tmpMenu = { privId: tmpNode.id }
        data.busMainData.rolePrivVOList.push(tmpMenu)
      })
      savePriv(data).then(res => {
        this.privLoading = false
        // this.update()
      }).catch(err => {
        this.privLoading = false
        console.log(err)
      })
    },
    saveMenu() {
      this.menuLoading = true
      const data = { busMainData: { id: this.currentId, roleMenuVOList: [] }}
      this.$refs.menu.getCheckedNodes().forEach(function(tmpNode, index) {
        if (!tmpNode.children) {
          const tmpMenu = { menuId: tmpNode.id }
          data.busMainData.roleMenuVOList.push(tmpMenu)
        }
      })
      saveMenu(data).then(res => {
        this.menuLoading = false
        // this.update()
      }).catch(err => {
        this.menuLoading = false
        console.log(err)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .role-span {
    font-weight: bold;color: #303133;
    font-size: 15px;
  }
</style>
